package cn.sstech.member.config;

import java.text.SimpleDateFormat;

import javax.servlet.MultipartConfigElement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import cn.sstech.member.core.util.FileUtil;

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
/* @Profile("dev") */
@PropertySource({ "classpath:config/persistence_${spring.profiles.active}.properties" })
public class MvcConfig extends WebMvcConfigurerAdapter {
	/*
	 * @Override public void addResourceHandlers(ResourceHandlerRegistry
	 * registry) { registry .addResourceHandler("/file/**")
	 * .addResourceLocations("/"+Paths.get("file").toString()+"/"); }
	 */

	@Value("${mvcconfig.webFilePath}")
	private String mvcconfig_webFilePath;

	@Value("${spring.profiles.active}")
	private String profilesActive;

	@Value("${mvc.allowedOrigins}")
	private String mvc_allowedOrigins;

	@Autowired
	FileUtil fileUtil;

	@Override
	public void addFormatters(FormatterRegistry formatterRegistry) {
		// formatterRegistry.addFormatter(new PermissionFormatter());
		// formatterRegistry.addFormatter(new RoleFormatter());
	}

	@Override
	/**
	 * 配置外部文件存放地址
	 */
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		// String webFileResourcePath = fileUtil.getClassPathRoot()
		// + "static"
		// + "/"
		// + "file"
		// + "/";
		//

		// webFileResourcePath = "file:" + webFileResourcePath;

		mvcconfig_webFilePath = "file:" + mvcconfig_webFilePath;

		registry.addResourceHandler("/file/**")
				// .addResourceHandler("/sites/**")
				// .addResourceLocations(mvcconfig_fileDirectoryResourceLocations);
				// .addResourceLocations(webFileResourcePath);
				.addResourceLocations(mvcconfig_webFilePath);
	}

	/**
	 * 文件上传临时路径，大小配置
	 */
	@Bean
	MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();

		// 文件上传后临时保存路径
		// factory.setLocation("d:/bbb/");
		// 文件最大
		factory.setMaxFileSize("5120KB");// KB,MB
		/// 设置总上传数据总大小
		factory.setMaxRequestSize("102400KB");
		return factory.createMultipartConfig();
	}

	@Bean
	@ConditionalOnMissingBean(ObjectMapper.class)
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();

		// 通过该方法对mapper对象进行设置，所有序列化的对象都将按改规则进行系列化
		// Include.Include.ALWAYS 默认
		// Include.NON_DEFAULT 属性为默认值不序列化
		// Include.NON_EMPTY 属性为 空（""） 或者为 NULL
		// 都不序列化，则返回的json是没有这个字段的。这样对移动端会更省流量
		// Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
		objectMapper.setSerializationInclusion(Include.NON_EMPTY);

		// Date 类型转 yyyy-MM-dd HH:mm:ss格式
		//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		// 字段保留，将null值转为""
		// objectMapper.getSerializerProvider().setNullValueSerializer(new
		// JsonSerializer<Object>()
		// {
		// @Override
		// public void serialize(Object o, JsonGenerator jsonGenerator,
		// SerializerProvider serializerProvider)
		// throws IOException, JsonProcessingException
		// {
		// jsonGenerator.writeString("");
		// }
		// });
		return objectMapper;
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {

		String[] allowedOrigins = mvc_allowedOrigins.split(",");

		registry.addMapping("/**").allowedOrigins(allowedOrigins)
				.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE").maxAge(3600).allowCredentials(true);

	}
}
